<?php
/**
 * Created by PhpStorm.
 * User: ken
 * Date: 2018/11/03
 * Time: 16:03
 */

namespace App\Libraries\Elasticsearch;

use Laravel\Scout\EngineManager;
use Illuminate\Support\ServiceProvider;
use Elasticsearch\ClientBuilder as ElasticBuilder;

/**
 * ElasticsearchProvider for elasticSearch
 *
 * @package App\Libraries\Elasticsearch
 */
class ElasticsearchProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     */
    public function boot()
    {
        $key = $this->getHttpAuthKey();

        app(EngineManager::class)->extend('elasticsearch', function ($app) use ($key) {
            return new ElasticsearchEngine(ElasticBuilder::create()
                ->setHosts(config('scout.elasticsearch.hosts'))
                ->setConnectionParams(array(
                    "client" => array(
                        "headers" => array(
                            "Authorization" => array($key)
                        )
                    )
                ))
                ->build(),
                config('scout.elasticsearch.index')
            );
        });
    }

    /**
     * 获取Es的基础http认证
     *
     * @return string
     */
    private function getHttpAuthKey()
    {
        $basic_auth_username = config("scout.elasticsearch.auth.user");
        $basic_auth_password = config("scout.elasticsearch.auth.password");

        //编码用户名和密码
        $key = base64_encode($basic_auth_username . ":" . $basic_auth_password);
        return "Basic " . $key;
    }
}
